﻿using AutoMapper;
using B.S.Backtrack.Domain.Entities;
using B.S.Backtrack.ErrorCode;
using B.S.Backtrack.Infrastructure.Interface;
using B.S.Backtrack.Write.API.Application.Command.Proces;
using MediatR;

namespace B.S.Backtrack.Write.API.Application.CommandHandler.Proces
{
    public class CreateProcessingHandler : IRequestHandler<CreateProcessingCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Processing> proRep;
        private readonly IMapper mapper;

        public CreateProcessingHandler(IBaseRepository<Processing> proRep,IMapper mapper)
        {
            this.proRep = proRep;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(CreateProcessingCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            //获取现有的实体
            var entity = proRep.GetAll().Where(x => x.ProductId == request.ProductId).FirstOrDefault();
            if (entity == null)
            {
                var model = mapper.Map<Processing>(request);
                proRep.Add(model);
                result.Code = ApiEnums.添加成功;
                result.Msg = ApiEnums.添加成功.ToString();
                result.Data = 1;
            }
            else
            {
                mapper.Map(request, entity);
                proRep.Update(entity);
                result.Code = ApiEnums.修改成功;
                result.Msg = ApiEnums.修改成功.ToString();
                result.Data = 1;
            }

            return Task.FromResult(result);
        }
    }
}
